//
//  SegmentPageScrollView.m
//  TKnowBox
//
//  Created by LiuXubin on 16/6/29.
//  Copyright © 2016年 knowin. All rights reserved.
//

#import "SimSegmentPageScrollView.h"
#import <SimPods/SimPageScrollView.h>
#import "SimBottomLineSegmentView.h"
#import <SimPods/UIView+SimAdditions.h>
#import <SimPods/SimDefine.h>

@interface SimSegmentPageScrollView ()<SimPageScrollViewDelegate,SimPageScrollViewDataSource>
{
    SimBottomLineSegmentView *_segmentView;
    SimPageScrollView *_pageScrollView;
    
    BOOL _lastTranslationIsUp;
    CGFloat _curTranslationY;
}

@end

@implementation SimSegmentPageScrollView

- (instancetype)initWithFrame:(CGRect)frame items:(NSArray *)items
{
    self = [super initWithFrame:frame];
    if (self) {
        self.showsHorizontalScrollIndicator = NO;
        self.showsVerticalScrollIndicator = NO;
        self.delegate = self;
        self.bounces = NO;
        
        _segmentView = [[SimBottomLineSegmentView alloc] initWithItems:items];
        [_segmentView addTarget:self action:@selector(clickOnSegment:) forControlEvents:UIControlEventValueChanged];
        _segmentView.size = CGSizeMake(self.width, 45);
        [self addSubview:_segmentView];
        
        _pageScrollView = [[SimPageScrollView alloc] initWithFrame:CGRectMake(0, _segmentView.bottom, self.width, self.height - _segmentView.height)];
        _pageScrollView.showsVerticalScrollIndicator = NO;
        _pageScrollView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        _pageScrollView.pageDelegate = self;
        _pageScrollView.dataSource = self;
        [self addSubview:_pageScrollView];
        
        self.headerView = nil;
    }
    
    return self;
}

- (void)dealloc
{
//    NSLog(@"SimSegmentPageScrollView dealloc");
}

- (NSArray *)items
{
    return _segmentView.items;
}

- (void)insertItem:(NSString *)item atIndex:(NSInteger)index
{
    [_pageScrollView clearAllPageView];
    [_segmentView insertItem:item atIndex:index];
    if (_segmentView.window != nil) {
        [self clickOnSegment:_segmentView];
    }
}

- (void)removeItemAtIndex:(NSInteger)index
{
    [_pageScrollView clearAllPageView];
    [_segmentView removeItemAtIndex:index];
    if (_segmentView.window != nil) {
        [self clickOnSegment:_segmentView];
    }
}

- (void)setHeaderView:(UIView *)headerView
{
    if (_headerView != headerView) {
        if (_headerView) {
            [_headerView removeFromSuperview];
        }
        _headerView = headerView;
        if (_headerView) {
            [self addSubview:_headerView];
            _segmentView.top = _headerView.bottom;
        }
        else{
            _segmentView.top = 0;
        }
    }
    _pageScrollView.top = _segmentView.bottom;
    _pageScrollView.height = self.height - _segmentView.height;
    self.contentSize = CGSizeMake(self.width, _pageScrollView.bottom);
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    _pageScrollView.top = _segmentView.bottom;
    _pageScrollView.height = self.height - _segmentView.height;
    self.contentSize = CGSizeMake(self.width, _pageScrollView.bottom);
}

- (BOOL)touchesShouldCancelInContentView:(UIView *)view
{
    return [view isKindOfClass:[UIButton class]];
}

- (UIScrollView *)pageScrollViewForView:(UIView *)pageView
{
    if ([pageView conformsToProtocol:@protocol(SegmentPageScrollViewProtocal)]) {
        return [(<SegmentPageScrollViewProtocal>)pageView innerScollView];
    }
    else{
        if (IsKindOfClass(pageView, UIScrollView)) {
            return (UIScrollView *)pageView;
        }
    }
    return nil;
}

- (UIScrollView *)curPageScrollView
{
    UIView *curPageView = [_pageScrollView curPageView];
    return [self pageScrollViewForView:curPageView];
}

- (void)subPageViewPanGesture:(UIPanGestureRecognizer *)recognizer
{
    if (self.headerView == nil) {
        return;
    }
    
    CGPoint velocity = [recognizer velocityInView:recognizer.view];
    CGPoint translation = [recognizer translationInView:recognizer.view];
    
    if (IsKindOfClass(recognizer.view, UIScrollView)) {
        UIScrollView *subScrollView = (UIScrollView *)recognizer.view;
//        NSLog(@"recognizer.state:%d velocity:%f translation:%f subScrollView:%f", recognizer.state, velocity.y, translation.y, subScrollView.contentOffset.y);
        if (subScrollView) {
            CGFloat maxOffY = [self contentMaxOffY];
            CGPoint offset = self.contentOffset;
            if (recognizer.state == UIGestureRecognizerStateEnded) {
                if (subScrollView.contentOffset.y == 0) {
                    if (_lastTranslationIsUp) { //滑松手时, 头部向上滑动，隐藏头部。
                        offset.y = maxOffY;
                    }
                    else if(_lastTranslationIsUp == NO){ //滑松手时, 头部向下滑动，显示头部。
                        offset.y = 0;
                    }
                    [self setContentOffset:offset animated:YES];
                }
            }
            else{
                if (recognizer.state == UIGestureRecognizerStateBegan){
                    _curTranslationY = translation.y;
                }
                
                //计算移动偏移量，向下拖>0, 向上拖<0
                CGFloat deltaTranslationY = translation.y - _curTranslationY;
                _curTranslationY = translation.y;
                if (abs(deltaTranslationY) >= 2) {
                    _lastTranslationIsUp = (deltaTranslationY < 0);
                }
//                NSLog(@"_lastTranslationIsUp:%d deltaTranslationY:%f", _lastTranslationIsUp, deltaTranslationY);
                
                if (deltaTranslationY > 0 && subScrollView.contentOffset.y > 0) {
                    return;
                }
                
                CGFloat deltaOffY = 0;
                offset.y -= deltaTranslationY;
                offset.y = Range(offset.y, 0, maxOffY);
                deltaOffY = offset.y - self.contentOffset.y;
                self.contentOffset = offset;
                
                if (abs(deltaOffY) > 0 || (offset.y > 0 && offset.y < maxOffY)) {
                    subScrollView.contentOffset = CGPointZero;
                }
                
            }
        }
    }
}

- (CGFloat)contentMaxOffY
{
    return floor(MAX(-1*self.contentInset.top, self.contentSize.height-self.height+self.contentInset.bottom));
}

- (void)removeTargetForContentView:(UIView *)contentView
{
    UIScrollView *scollView = [self pageScrollViewForView:contentView];
    [scollView.panGestureRecognizer removeTarget:self action:@selector(subPageViewPanGesture:)];
}

#pragma mark - SimBottomLineSegmentView
- (void)clickOnSegment:(SimBottomLineSegmentView *)segmentView
{
    [_pageScrollView displayPage:segmentView.selectedSegmentIndex animated:YES];
}

#pragma mark - SimPageScrollViewDelegate
- (void)pageScrollView:(SimPageScrollView *)scrollView didShowPage:(NSInteger)pageIndex
{
    _segmentView.selectedSegmentIndex = pageIndex;
    if (_showViewAtIndexBlock) {
        _showViewAtIndexBlock(pageIndex);
    }
}

#pragma mark - SimPageScrollViewDataSource

- (UIView *)viewForScrollView:(SimPageScrollView *)scrollView page:(NSInteger)pageIndex
{
    UIView *contentView = nil;
    if (_conentViewAtIndexBlock) {
        contentView = _conentViewAtIndexBlock(pageIndex);
    }
    
    UIScrollView *scollView = [self pageScrollViewForView:contentView];
    [scollView.panGestureRecognizer addTarget:self action:@selector(subPageViewPanGesture:)];
    
    return contentView;
}

- (NSInteger)numberOfPagesForPageScrollView:(SimPageScrollView *)scrollView
{
    return _segmentView.items.count;
}

@end
